<template>
  <div class="relatime">
    <div class="relatime-top">
      <div class="top">
        <el-checkbox
          v-model="checked2"
          label="A侧"
          size="large"
          @change="changeQuery"
        />
        <el-checkbox
          v-model="checked3"
          label="B侧"
          size="large"
          @change="changeQuery"
        />
        <el-select
          v-model="time"
          placeholder="请选择曲线时间区间"
          style="width: 165px"
        >
          <el-option
            v-for="item in timeList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
        <el-date-picker
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="datePicker"
          placeholder="选择日期时间"
          :disabled-date="disabledDate"
          :disabled-hours="disabledHours"
          :disabled-minutes="disabledMinutes"
          :disabled-seconds="disabledSeconds"
        ></el-date-picker>
        <el-button type="primary" @click="getHistory()">查询</el-button>
      </div>
      <div class="center">
        <div class="charts-box" ref="chartBox1"></div>
      </div>
    </div>
    <div class="relatime-bottom">
      <div class="top">
        <p>历史数据</p>
      </div>
      <div class="center">
        <el-row>
          <el-col :span="6" v-for="(item, key) in dataList" :key="key">
            <el-row v-if="item.name != ''">
              <el-col :span="3"></el-col>
              <el-col :span="18">
                <div class="item">
                  <div class="name">
                    <p>{{ item.name }}</p>
                  </div>
                  <div class="value">
                    <p>{{ item.value }}</p>
                  </div>
                  <div class="dw">
                    <p>{{ item.dw }}</p>
                  </div>
                </div>
              </el-col>
              <el-col :span="3"></el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import { history } from "../http/api";
import { ElMessage } from "element-plus";
const data = reactive({
  location: "A",
  locationList: [
    {
      label: "请选择测量位置",
      value: "",
    },
    {
      label: "A测",
      value: "A",
    },
    {
      label: "B测",
      value: "B",
    },
  ],
  time: "5min",
  timeList: [
    {
      label: "请选择曲线时间区间",
      value: "",
    },
    {
      label: "5min",
      value: "5min",
    },
    {
      label: "10min",
      value: "10min",
    },
    {
      label: "1h",
      value: "1h",
    },
    {
      label: "4h",
      value: "4h",
    },
    {
      label: "8h",
      value: "8h",
    },
    {
      label: "60h",
      value: "60h",
    },
  ],
  dataList: [
    {
      id: 1,
      name: "A测实测氧量",
      value: 120,
      dw: "%",
      bg: "yellow",
      key: "oxygenA_real",
    },
    {
      id: 2,
      name: "B测实测氧量",
      value: 120,
      dw: "%",
      bg: "yellow",
      key: "oxygenB_real",
    },
    {
      id: 3,
      name: "机组负荷",
      value: 120,
      dw: "MW",
      key: "unitLoad",
    },
    {
      id: 4,
      name: "A磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowA",
    },
    {
      id: 5,
      name: "A测预测氧量",
      value: 120,
      dw: "%",
      bg: "hong",
      key: "oxygenA_predict",
    },
    {
      id: 6,
      name: "B测预测氧量",
      value: 120,
      dw: "%",
      bg: "hong",
      key: "oxygenB_predict",
    },
    {
      id: 7,
      name: "主汽压力",
      value: 120,
      dw: "Mpa",
      key: "mainSteamPressure",
    },
    {
      id: 8,
      name: "B磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowB",
    },
    {
      id: 9,
      name: "A测融合氧量",
      value: 120,
      dw: "%",
      bg: "lv",
      key: "oxygenA_merge",
    },
    {
      id: 10,
      name: "B测融合氧量",
      value: 120,
      dw: "%",
      bg: "lv",
      key: "oxygenB_merge",
    },
    {
      id: 11,
      name: "主汽温度",
      value: 120,
      dw: "℃",
      key: "mainSteamTemperature",
    },
    {
      id: 12,
      name: "C磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowC",
    },
    {
      id: 13,
      name: "A测一次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowA_primary",
    },
    {
      id: 14,
      name: "B测一次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowB_primary",
    },
    {
      id: 15,
      name: "炉膛负压",
      value: 120,
      dw: "Pa",
      key: "furnace_pressure",
    },
    {
      id: 16,
      name: "D磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowD",
    },
    {
      id: 17,
      name: "A测二次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowA_secondary",
    },
    {
      id: 18,
      name: "B测二次风量",
      value: 120,
      dw: "t/h",
      key: "airFlowB_secondary",
    },
    {
      id: 19,
      name: "一次总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_primary",
    },
    {
      id: 20,
      name: "E磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowE",
    },
    {
      id: 21,
      name: "A侧一次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureA_primary",
    },
    {
      id: 22,
      name: "B侧一次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureB_primary",
    },
    {
      id: 23,
      name: "二次总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_secondary",
    },
    {
      id: 24,
      name: "F磨煤量",
      value: 120,
      dw: "t/h",
      key: "fuelFlowF",
    },
    {
      id: 25,
      name: "A侧二次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureA_secondary",
    },
    {
      id: 26,
      name: "B侧二次风压",
      value: 120,
      dw: "kPa",
      key: "airPressureB_secondary",
    },
    {
      id: 27,
      name: "炉膛总风量",
      value: 120,
      dw: "t/h",
      key: "airFlow_total",
    },
    {
      id: 28,
      name: "",
      value: "",
      dw: "",
      key: "",
    },
    {
      id: 29,
      name: "A侧实测CO量",
      value: 120,
      dw: "ppm",
      key: "COA_real",
    },
    {
      id: 30,
      name: "B侧实测CO量",
      value: 120,
      dw: "ppm",
      key: "COB_real",
    },
  ],
  datePicker: "",
  checked2: true,
  checked3: false,
  checked1List: [
    {
      key: "oxygenA_merge",
      label: "A侧融合氧量",
    },
    {
      key: "oxygenA_predict",
      label: "A侧预测氧量",
    },
    {
      key: "oxygenA_real",
      label: "A侧实测氧量",
    },
  ],
  checked2List: [
    {
      key: "oxygenB_merge",
      label: "B侧融合氧量",
    },
    {
      key: "oxygenB_predict",
      label: "B侧预测氧量",
    },
    {
      key: "oxygenB_real",
      label: "B侧实测氧量",
    },
  ],
  xyList: {
    xData: [],
    yData: [],
    legend: [],
  },
  newCheckedList: [],
  groupedByList: [],
});
const {
  location,
  locationList,
  time,
  timeList,
  dataList,
  datePicker,
  checked2,
  checked3,
  checked1List,
  checked2List,
  xyList,
  newCheckedList,
  groupedByList,
} = toRefs(data);
const chartBox1 = ref(null);
let chartOne = undefined;
function initChart() {
  drawChart();
}
function chartOneMouseMove(index, value) {
  dataList.value.map((item) => {
    item.value = item.key
      ? Number(groupedByList.value[item.key][index].value).toFixed(2)
      : "";
  });
}
function drawChart() {
  if (!chartOne) {
    chartOne = echarts.init(chartBox1.value, "macarons");
  }
  let option = {
    legend: {
      show: true,
      top: 15,
      textStyle: { color: "#ffffff" },
      data: xyList.value.legend,
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
      axisPointer: {
        animation: false,
      },
      cofine: true,
    },
    grid: {
      top: 50,
      left: 30,
      right: 30,
      bottom: 40,
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: xyList.value.xData,
      axisLine: { lineStyle: { color: "#ccc" } },
      axisTick: { length: 3 },
      axisLabel: { color: "#999" },
    },
    yAxis: {
      name: "氧量/%",
      type: "value",
      axisLine: { show: true, lineStyle: { color: "#ccc" } },
      axisLabel: { color: "#999" },
      splitLine: { show: false },
    },
    series: xyList.value.yData,
    animationDuration: 0,
    animationEasing: "cubicInOut",
  };
  chartOne.setOption(option, true);
  chartOne.on("highlight", (param) => {
    // console.log(
    //   xyList.value.xData,
    //   xyList.value.yData[0].data,
    //   xyList.value.xData[param.dataIndex],
    //   xyList.value.yData[0].data[param.dataIndex],
    //   param,
    //   groupedByList.value["oxygenA_merge"]
    // );
    chartOneMouseMove(param.batch[0].dataIndex);
  });
}
function getFormatTime(stamp) {
  // stamp = stamp * 1000;
  let data = stamp ? new Date(stamp) : new Date();
  let year = data.getFullYear();
  let month = data.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let date = data.getDate();
  date = date < 10 ? "0" + date : date;
  return (
    year +
    "-" +
    month +
    "-" +
    date +
    " " +
    new Date(stamp).toLocaleTimeString("chinese", { hour12: false })
  );
}
function getStartEndTime(time, dw) {
  let curDate = datePicker.value
    ? new Date(datePicker.value).getTime()
    : new Date().getTime();
  // let start = curDate - (time / 2) * 60 * 1000;
  // let end = curDate + (time / 2) * 60 * 1000;
  let start;
  if (dw == "min") {
    start = getFormatTime(curDate - time * 60 * 1000);
  }
  if (dw == "h") {
    start = getFormatTime(curDate - time * 60 * 60 * 1000);
  }
  let end = getFormatTime(curDate);
  // st.value = start;
  // et.value = end;
  return {
    start: start,
    end: end,
  };
}
async function changeQuery() {
  newCheckedList.value = [];
  if (checked2.value == true && checked3.value == false) {
    newCheckedList.value = checked1List.value;
  }
  if (checked2.value == false && checked3.value == true) {
    newCheckedList.value = checked2List.value;
  }
  if (checked2.value == true && checked3.value == true) {
    newCheckedList.value = checked1List.value.concat(checked2List.value);
  }
  if (checked2.value == false && checked3.value == false) {
    checked2.value = true;
    newCheckedList.value = checked1List.value;
    ElMessage({
      type: "error",
      message: "至少选择一侧",
    });
  }

  if (chartOne) {
    chartOne.clear();
    xyList.value = relatimeCurveFn(groupedByList.value);
    initChart();
  }
}
function relatimeCurveFn(data) {
  let xData = [];
  let yData = [];
  let legend = [];
  let valueList =
    newCheckedList.value.length > 0 ? newCheckedList.value : checked1List.value;
  valueList.map((item, index) => {
    let yDataParam = [];
    legend.push(item.label);
    data[item.key].map((child, childIndex) => {
      if (index == 0) {
        xData.push(child.timestamp);
      }
      yDataParam.push(child.value);
    });

    let param = {
      name: item.label,
      label: item.key,
      type: "line",
      smooth: true, // 平滑曲线
      showSymbol: false,
      data: yDataParam,
    };
    yData.push(param);
  });
  return {
    xData,
    yData,
    legend,
  };
}
function getHistory() {
  if (time.value == "") {
    ElMessage({
      type: "error",
      message: "请选择时间曲线间隔",
    });
    return;
  }
  datePicker.value = datePicker.value
    ? getFormatTime(new Date(datePicker.value).getTime())
    : getFormatTime(new Date().getTime());

  let times = getStartEndTime(
    time.value.indexOf("min") != -1
      ? time.value.replaceAll("min", "")
      : time.value.replaceAll("h", ""),
    time.value.indexOf("min") != -1 ? "min" : "h"
  );
  let param = {
    time_unit: time.value,
    start_time: times.start,
    end_time: times.end,
  };
  history(param).then((res) => {
    groupedByList.value = res.reduce((acc, item) => {
      if (!acc[item.name]) {
        acc[item.name] = [];
      }
      acc[item.name].push(item);
      return acc;
    }, {});
    console.log(groupedByList.value);

    dataList.value.map((item) => {
      item.value = item.key
        ? Number(
            groupedByList.value[item.key][
              groupedByList.value[item.key].length - 1
            ].value
          ).toFixed(2)
        : "";
    });
    xyList.value = relatimeCurveFn(groupedByList.value);
    initChart();
  });
}

function disabledDate(data) {
  return data > new Date();
}
const disabledHours = () => {
  const hours = [];
  for (let i = new Date().getHours() + 1; i < 24; i++) {
    hours.push(i);
  }
  return hours;
};
const disabledMinutes = (selectedHour) => {
  if (selectedHour === new Date().getHours()) {
    const minutes = [];
    for (let i = new Date().getMinutes() + 1; i < 60; i++) {
      minutes.push(i);
    }
    return minutes;
  }
  return [];
};
const disabledSeconds = (hour, minute) => {
  if (hour === new Date().getHours() && minute === new Date().getMinutes()) {
    const seconds = [];
    for (let i = new Date().getSeconds() + 1; i < 60; i++) {
      seconds.push(i);
    }
    return seconds;
  }
  return [];
};

onActivated(() => {
  getHistory();
});
//initChart();
</script>
<style lang="scss">
.relatime {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  .relatime-top,
  .relatime-bottom {
    width: 100%;
    height: 49%;
    border: 1px solid #319efd;
    background: url(../assets/img/kuang.png) center center no-repeat;
    background-size: cover;
  }
  .relatime-top {
    .top {
      width: 100%;
      height: 5.3vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .center {
      width: 100%;
      height: calc(100% - 5.3vh);
      .charts-box {
        width: 100%;
        height: 100%;
      }
    }
  }
  .relatime-bottom {
    padding: 9px;
    .top {
      width: 21vw;
      height: 4.7vh;
      position: relative;
      background: url(../assets/img/title-bt.png) center center no-repeat;
      background-size: cover;
      display: flex;
      justify-content: flex-start;
      p {
        font-family: Source Han Sans CN;
        font-weight: bold;
        margin-left: 30px;
        font-size: 22px;
        color: #daedff;
        line-height: 27px;
        background: linear-gradient(
          0deg,
          #79c5ff 0%,
          #ffffff 59.8388671875%,
          #ffffff 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    .center {
      width: 100%;
      height: calc(100% - 5.3vh);
      .el-row {
        height: 100%;
        .item {
          height: 100%;
          display: flex;
          align-items: center;
          .name {
            width: 120px;
            min-height: 27px;
            background: url(../assets/img/key-lan.png) center center no-repeat;
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #011750;
            }
          }
          .name.hong {
            background: url(../assets/img/key-hong.png) center center no-repeat;
            background-size: cover;
          }
          .name.lv {
            background: url(../assets/img/key-lv.png) center center no-repeat;
            background-size: cover;
          }
          .name.yellow {
            background: url(../assets/img/key-huang.png) center center no-repeat;
            background-size: cover;
          }
          .value {
            width: 5.3vw;
            min-height: 27px;
            border: 1px solid;
            border-image: linear-gradient(0deg, #02b0fe, #72fbf6) 10 10;
            display: flex;
            justify-content: center;
            align-items: center;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #16bdfd;
              line-height: 25px;
            }
          }
          .value.hong {
            border: 1px solid;
            border-image: linear-gradient(0deg, #ff7877, #ffdfd3) 10 10;
            p {
              color: #ff7878;
            }
          }
          .value.lv {
            border: 1px solid;
            border-image: linear-gradient(0deg, #56dd6f, #cdffd6) 10 10;
            p {
              color: #48eb67;
            }
          }
          .value.yellow {
            border: 1px solid;
            border-image: linear-gradient(0deg, #dcb51b, #fdf3cf) 10 10;
            p {
              color: #ffd633;
            }
          }
          .dw {
            width: 40px;
            margin: 3px;
            p {
              font-family: PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #16bdfd;
            }
          }
          .dw.hong {
            p {
              color: #ff7878;
            }
          }
          .dw.lv {
            p {
              color: #48eb67;
            }
          }
          .dw.yellow {
            p {
              color: #ffd633;
            }
          }
        }
      }
    }
  }
}
</style>
